package com.fatcat.easybuy.service.impl;

import com.fatcat.easybuy.exception.BusinessException;
import com.fatcat.easybuy.mapper.EasyBuyOrderMapper;
import com.fatcat.easybuy.pojo.*;
import com.fatcat.easybuy.service.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;


/**
 * @author Fatcat
 * @description 针对表【easybuy_order】的数据库操作Service实现
 * @createDate 2025-09-10 10:52:53
 */
@Service
public class EasyBuyOrderServiceImpl implements EasyBuyOrderService {
    // 订单支付超时时间：20分钟（单位：秒）
    private static final long PAY_TIMEOUT_SECONDS = 20 * 60;
    // 订单过期键前缀
    private static final String ORDER_EXPIRE_KEY_PREFIX = "order:";
    @Autowired
    private EasyBuyOrderMapper orderMapper;
    @Autowired
    private EasyBuyOrderDetailService orderDetailService;
    @Autowired
    private EasyBuyProductService productService;
    @Autowired
    private EasyBuyUserAddressService userAddressService;
    @Autowired
    private EasyBuyUserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    private final String SHOPPING_CART_HASH = "shoppingCartHash:";
    private final String SHOPPING_CART_ZSET = "shoppingCartzSet:";

    private static final Logger LOGGER = LoggerFactory.getLogger(EasyBuyOrderServiceImpl.class);

    @Override
    public PageInfo<EasyBuyOrder> selectAllOrder(Map<String, Object> params) {
        PageHelper.startPage(params);
        List<EasyBuyOrder> orderList = orderMapper.selectAllOrder(params);
        for (EasyBuyOrder order : orderList) {
            if (order.getStatus() == 1) {
                String redisKey = ORDER_EXPIRE_KEY_PREFIX + order.getId();
                //无redis，及订单过期，关闭订单
                if (stringRedisTemplate.opsForValue().get(redisKey) == null) {
                    closeOrder(order.getSerialNumber());
                    LOGGER.info("订单号为{}的订单已过期，已关闭", order.getSerialNumber());
                }
            }
        }
        return new PageInfo<>(orderList);
    }

    @Override
    @Transactional
    public boolean addOrder(Map<Long, Integer> productIdAndQuantity, Long userId, Integer addressId) {
//检查订单
        if (productIdAndQuantity.isEmpty()) {
            throw new BusinessException("请选择商品");
        }
        Set<Long> productIds = productIdAndQuantity.keySet();
        // 批量查询商品
        List<EasyBuyProduct> productList = productService.getProductsByIds(new ArrayList<>(productIds));
        if (productIds.size() != productList.size()) {
            throw new BusinessException("商品不存在");
        }

        // ID->商品
        Map<Long, EasyBuyProduct> productMap = new HashMap<>();
        for (EasyBuyProduct product : productList) {
            productMap.put(product.getId(), product);
        }
        for (Long productId : productIds) {
            EasyBuyProduct product = productMap.get(productId);
            Integer quantity = productIdAndQuantity.get(productId);
            if (product.getStock() < quantity) {
                throw new BusinessException("商品" + product.getProductName() + "库存不足");
            }
        }
        //添加总订单
        Long orderId = addMainOrder(userId, addressId);//订单id
        if (orderId == null) {
            return false;
        }
        //添加详细订单
        double totalCost = addDetailOrder(productIdAndQuantity, productMap, orderId);
        // 更新订单总金额
        EasyBuyOrder easyBuyOrder = getOrderById(orderId);
        easyBuyOrder.setCost(totalCost);
        // 更新订单
        boolean orderBool = false;
        try {
            orderBool = orderMapper.updateOrder(easyBuyOrder) > 0;
            //更新商品临时库存
            productService.updateProductTempStockByOutOrderNo(easyBuyOrder.getSerialNumber());
            //更新商品正式库存
            productService.updateProductStockByOutOrderNo(easyBuyOrder.getSerialNumber());
            //清空购物车
            redisTemplate.delete(SHOPPING_CART_HASH + userId);
            redisTemplate.delete(SHOPPING_CART_ZSET + userId);
        } catch (Exception e) {
            throw new BusinessException("创建订单失败", e);
        }
        //清空购物车

        if (orderBool) {
            // 存储订单过期时间到 Redis
            String redisKey = ORDER_EXPIRE_KEY_PREFIX + easyBuyOrder.getId();
            stringRedisTemplate.opsForValue().set(redisKey, easyBuyOrder.getSerialNumber(), PAY_TIMEOUT_SECONDS, TimeUnit.SECONDS);
            return true;
        }
        return false;
    }


    @Override
    @Transactional
    public boolean closeOrder(String serialNumber) {
        EasyBuyOrder easyBuyOrder = getOrderBySerialNumber(serialNumber);
        if (easyBuyOrder == null) {
            throw new BusinessException("订单不存在");
        }
        if (easyBuyOrder.getStatus() != 3) {
            try {
                int rows = orderMapper.closeOrder(serialNumber);
                if (rows > 0) {
                    //回滚预出库库存
                    productService.updateProductTempStockRollbackByOutOrderNo(serialNumber);
                    //回滚商品正式库存
                    productService.updateProductStockRollbackByOutOrderNo(serialNumber);
                    // 关闭订单后删除Redis缓存
                    stringRedisTemplate.delete(ORDER_EXPIRE_KEY_PREFIX + easyBuyOrder.getId());
                    return true;
                }
                return false;
            } catch (Exception e) {
                LOGGER.error("关闭订单失败，订单ID：{}", easyBuyOrder.getId(), e);
                throw new BusinessException("关闭订单失败", e);
            }
        }
        return true;
    }


    @Override
    public EasyBuyOrder getOrderBySerialNumber(String outTradeNo) {
        return orderMapper.selectOrderBySerialNumber(outTradeNo);
    }

    @Transactional
    @Override
    public boolean updateOrder(EasyBuyOrder easyBuyOrder) {
        try {
            return orderMapper.updateOrder(easyBuyOrder) > 0;
        } catch (Exception e) {
            throw new BusinessException("更新订单失败", e);
        }
    }

    @Override
    public EasyBuyOrder getOrderById(Long orderId) {
        return orderMapper.selectOrderById(orderId);
    }

    @Override
    @Transactional
    public boolean deleteOrder(Long orderId) {
        try {
            int rows = orderMapper.deleteOrder(orderId);
            if (rows <= 0) {
                throw new BusinessException("删除失败：订单不存在（ID=" + orderId + "）");
            }
            return true;
        } catch (Exception e) {
            throw new BusinessException("删除订单时发生数据库错误", e);
        }
    }

    @Transactional
    @Override
    public boolean changeStatus(Long orderId, Integer status) {
        try {
            return orderMapper.changeStatus(orderId, status) > 0;
        } catch (Exception e) {
            throw new BusinessException("修改订单状态失败", e);
        }
    }

    //保存总订单
    private Long addMainOrder(Long userId, Integer addressId) {
        //订单用户
        EasyBuyUser user = userService.getUserById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        //订单地址
        String address = userAddressService.getAddressById(addressId);
        if (address == null) {
            throw new BusinessException("地址不存在");
        }

        //订单号
        String serialNumber = UUID.randomUUID().toString().replace("-", "").toUpperCase();
        //组装订单实体
        EasyBuyOrder easyBuyOrder = new EasyBuyOrder();
        easyBuyOrder.setUserId(userId);
        easyBuyOrder.setLoginName(user.getLoginName());
        easyBuyOrder.setUserAddress(address);
        easyBuyOrder.setSerialNumber(serialNumber);
        // 保存订单
        try {
            if (orderMapper.addOrder(easyBuyOrder) > 0) {
                return easyBuyOrder.getId();
            } else {
                return null;
            }
        } catch (Exception e) {
            LOGGER.error("主订单创建异常，用户ID：{}", userId, e);
            throw new BusinessException("新增订单失败", e);
        }
    }

    //添加详细订单
    private double addDetailOrder(Map<Long, Integer> productIdAndQuantity, Map<Long, EasyBuyProduct> productMap, Long orderId) {

        List<EasyBuyOrderDetail> detailList = new ArrayList<>();
        double totalCost = 0.0;
        //遍历,构建商品详情
        for (Map.Entry<Long, Integer> entry : productIdAndQuantity.entrySet()) {
            Long productId = entry.getKey();
            Integer quantity = entry.getValue();

            // 验证购买数量
            if (quantity <= 0) {
                LOGGER.error("商品ID为{}的购买数量必须大于0", productId);
                throw new BusinessException("商品ID为" + productId + "的购买数量必须大于0");
            }

            // 获取商品信息
            EasyBuyProduct product = productMap.get(productId);

            // 计算金额
            double unitPrice = product.getPrice();
            //每单商品金额
            double itemTotal = unitPrice * quantity;
            //总金额
            totalCost += itemTotal;

            // 构建订单详情
            EasyBuyOrderDetail detail = new EasyBuyOrderDetail();
            detail.setOrderId(orderId);
            detail.setProductId(productId);
            detail.setQuantity(quantity);
            detail.setCost(itemTotal);
            detailList.add(detail);
        }
        // 保存订单详情
        try {
            orderDetailService.addAllOrderDetail(detailList);
        } catch (Exception e) {
            throw new BusinessException("新增订单详情失败", e);
        }
        return totalCost;
    }
}
